package com.yxc.demo3.controller;

import com.yxc.demo3.vo.ResultVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class FileUploadController {

    @Value("${web.upload-path}")
    private String realPath;

    @PostMapping
    public ResultVo upload(MultipartFile file) {
        return getUpload(file);

    }

    @PostMapping("/s")
    public ResultVo uploads(MultipartFile[] files) {
        for (MultipartFile file : files) {
            return getUpload(file);
        }
        return ResultVo.success("文件上传成功", null);
    }

    private ResultVo getUpload(MultipartFile file) {
        if (!file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.indexOf("."));
            if (file.getSize() > 500 * 1024) {
                throw new RuntimeException("文件大于500k");
            } else if (suffix.equalsIgnoreCase(".jpg") ||
                    suffix.equalsIgnoreCase(".png") ||
                    suffix.equalsIgnoreCase(".jpeg") ||
                    suffix.equalsIgnoreCase(".gif")) {
                //默认是上传到项目的webapp下
                File savePath = new File(realPath);
                if (!savePath.exists()) {
                    savePath.mkdirs();
                }
                String fileName = UUID.randomUUID().toString().replace("-", "");

                File saveFile = new File(realPath + fileName + suffix);
                try {
                    file.transferTo(saveFile);
                    return ResultVo.success("文件上传成功", null);
                } catch (IOException e) {
                    throw new RuntimeException("上传出现异常");
                }
            } else {
                throw new RuntimeException("文件格式错误");
            }
        } else {
            throw new RuntimeException("文件必传");
        }
    }
}